import React, { useEffect, useRef, useState } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import {
  Divider,
  Button,
  Table,
  Tooltip,
  Spin,
  Popconfirm,
  message,
} from 'antd';
import { PlusOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons';
import Search from './Search';
import { history } from 'umi';
import Detail from './Detail';
import { connect } from 'dva';
import { useRequest, useUpdateEffect, useSize } from '@umijs/hooks';
import {
  apiOrderAdd,
  apiOrderDelete,
  apiOrderGetList,
  apiOrderUpdate,
  apiOrderGetChildrenList,
} from '@/services/otherServices';
import {
  btnPermission,
  diffSubmitData,
  formatDate,
  formatDateTimeStamp,
  mergeLoading,
} from '@/utils/utils';
import { orderStateEnum } from '@/utils/constant';
import HehDescribe from '@/components/HehDescribe';
import moment from 'moment';

let detailForm: any = null;
const List = (props: any) => {
  const dom = document.getElementById('heh-table');
  const donSize = useSize(dom);

  const { btnPermissionLoading, childrenCollapsed, match } = props;
  const actionRef = useRef<ActionType>();
  const [decVisible, setDecVisible] = useState(false);
  const [decInfo, setDecInfo] = useState(false);

  const [visible, setVisible] = useState(false);
  const [size, setSize]: any = useState('large');
  const [searchValue, setSearchValue] = useState({});
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [x, setX] = useState({ x: '100%' });
  const [pageSize, setPageSize]: any = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [editId, setEditId] = useState(undefined);
  const [editItem, setEditItem] = useState(undefined);

  const [childPageData, setChildPageData]: any = useState({});
  /*
   * 列表请求
   * */
  const { loading: pageLoading, run: getPage } = useRequest(apiOrderGetList, {
    manual: true,
    onSuccess: (res, params) => {
      setDataSource(res.data);
      setTotal(res.total);
    },
  });

  /*
   * 获取子订单请求
   * */
  const { loading: childPageLoading, run: getChildPage } = useRequest(
    apiOrderGetChildrenList,
    {
      manual: true,
      debounceInterval: 500,
      onSuccess: (res, params: any) => {
        setChildPageData({
          ...childPageData,
          [params[0].parentId]: {
            loading: false,
            data: res.data,
            total: res.total,
            pageNo: res.pageNo,
          },
        });
      },
    },
  );

  /*
   * 新建请求
   * */
  const { loading: addLoading, run: add } = useRequest(apiOrderAdd, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params: any) => {
      message.success('添加成功');
      setVisible(false);
      if (params[0].parentId === 0) {
        getPageData();
      } else {
        getChildPage({
          pageNo: 1,
          pageSize: 10,
          parentId: params[0].parentId,
        });
        setChildPageData({
          ...childPageData,
          [params[0].parentId]: {
            loading: true,
            pageNo: 1,
          },
        });
      }
    },
  });

  /*
   * 编辑请求
   * */
  const { loading: updateLoading, run: update } = useRequest(apiOrderUpdate, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params: any) => {
      message.success('更新成功');
      setVisible(false);
      if (params[0].parentId === 0) {
        getPageData();
      } else {
        console.log(params);
        getChildPage({
          pageNo: 1,
          pageSize: 10,
          parentId: params[0].parentId,
        });
        setChildPageData({
          ...childPageData,
          [params[0].parentId]: {
            loading: true,
            pageNo: 1,
          },
        });
      }
    },
  });

  /*
   * 删除请求
   * */
  const { loading: delLoading, run: del } = useRequest(apiOrderDelete, {
    manual: true,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('删除成功');
      if (total % 10 === 1) {
        setCurrent(current - 1);
      } else {
        getPageData();
      }
    },
  });

  /*
   * 删除请求
   * */
  const { loading: childDelLoading, run: childDel } = useRequest(
    apiOrderDelete,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('删除成功');
      },
    },
  );

  const getPageData = (sort?: string) => {
    getPage({
      status: 1,
      pageNo: current,
      pageSize: pageSize,
      ...searchValue,
    });
  };

  useUpdateEffect(() => {
    getPageData();
  }, [current, pageSize, searchValue]);

  useUpdateEffect(() => {
    setWidth(true);
  }, [childrenCollapsed]);

  useUpdateEffect(() => {
    const { params } = match;
    getPageData(params?.sort);
  }, [match]);

  useEffect(() => {
    getPageData();
    setWidth();
  }, []);

  const setWidth = (tag?: boolean) => {
    var box = document.getElementById('calculate-body');
    let width: number = box?.clientWidth || 1000;
    if (tag) {
      if (childrenCollapsed) {
        width = width + 176;
      } else {
        width = width - 176;
      }
    }
    if (width >= 1000 && width <= 1100) {
      setX({ x: `${0.13 * width}%` });
    } else if (width > 1100 && width <= 1200) {
      setX({ x: `${0.122 * width}%` });
    } else if (width > 1200 && width <= 1300) {
      setX({ x: `${0.09 * width}%` });
    } else if (width > 1300 && width <= 1350) {
      setX({ x: `${0.09 * width}%` });
    } else {
      setX({ x: `100%` });
    }
  };
  const expandedRowRender = (record: any) => {
    const columns: ProColumns<any>[] = [
      { title: '子订单编号', dataIndex: 'orderNo', key: 'orderNo' },
      {
        title: '分公司',
        dataIndex: 'productCompany',
      },
      { title: '产品', dataIndex: 'productName', key: 'productName' },
      { title: '规格', dataIndex: 'spec', key: 'spec' },
      { title: '数量', dataIndex: 'amount', key: 'amount' },
      { title: '单位', dataIndex: 'unit', key: 'unit' },
      {
        title: '备注',
        dataIndex: 'remark',
        width: 200,
        ellipsis: true,
      },
    ];
    if (
      btnPermission(history.location.pathname, [
        'btn_order_stock_edit',
        'btn_order_stock_del',
      ])
    ) {
      columns.push({
        title: '操作',
        width: 80,
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => (
          <>
            {btnPermission(
              history.location.pathname,
              'btn_order_stock_edit',
            ) && (
              <span>
                <a
                  onClick={() => {
                    if (record.orderTime) {
                      record.orderTime = moment(record.orderTime);
                    }
                    if (record.deliveryDate) {
                      record.deliveryDate = moment(record.deliveryDate);
                    }
                    detailForm.setFieldsValue({
                      ...record,
                    });
                    setVisible(true);
                    setEditId(record.id);
                    setEditItem(record);
                  }}
                >
                  <Tooltip mouseEnterDelay={0.5} title="编辑">
                    <FormOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </span>
            )}
            {btnPermission(
              history.location.pathname,
              'btn_order_stock_del',
            ) && (
              <span>
                <Divider type="vertical" />
                <Popconfirm
                  title="确认删除？"
                  placement="topRight"
                  okText="确认"
                  cancelText="取消"
                  onConfirm={() => {
                    childDel(record.id);
                    if (
                      record.parentId !== undefined &&
                      record.parentId !== 0
                    ) {
                      getChildPage({
                        pageNo: 1,
                        pageSize: 10,
                        parentId: record.parentId,
                      });
                      setChildPageData({
                        ...childPageData,
                        [record.parentId]: {
                          loading: true,
                          pageNo: 1,
                        },
                      });
                    }
                  }}
                >
                  <a>
                    <Tooltip mouseEnterDelay={0.5} title="删除">
                      <DeleteOutlined style={{ fontSize: 18 }} />
                    </Tooltip>
                  </a>
                </Popconfirm>
              </span>
            )}
          </>
        ),
      });
    }
    const data: any = childPageData[record.id]?.data || [];
    const loading: any = childPageData[record.id]?.loading || false;
    const total: any = childPageData[record.id]?.total || false;
    const pageNo: any = childPageData[record.id]?.pageNo || false;
    if (loading === true) {
      return (
        <div style={{ textAlign: 'center' }}>
          <Spin spinning={loading} />
        </div>
      );
    }
    if (data.length === 0 && loading === false) {
      return null;
      // return <p style={{ margin: 0, textAlign: 'center' }}>无子订单信息</p>;
    }
    return (
      <Table
        // @ts-ignore
        columns={columns}
        rowKey={'id'}
        dataSource={data}
        size={'middle'}
        bordered
        scroll={{ x: 'max-content' }}
        style={{ padding: 16 }}
        pagination={{
          pageSize: 10,
          total: total,
          hideOnSinglePage: true,
          current: pageNo,
          onChange: (page, pageSize) => {
            getChildPage({
              pageNo: page,
              pageSize: 10,
              parentId: record.id,
            });

            setChildPageData({
              ...childPageData,
              [record.id]: {
                loading: true,
                pageNo: page,
              },
            });
          },
        }}
      />
    );
  };

  const columns: any[] = [
    {
      title: '编号',
      dataIndex: 'a',
      render: (text: any, record: any, index: any) => (
        <span>{(current - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: '分公司',
      dataIndex: 'productCompany',
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
    },
    {
      title: '客户单位',
      dataIndex: 'customerCompany',
    },
    {
      title: '品名',
      dataIndex: 'productName',
    },
    {
      title: '颜色',
      dataIndex: 'color',
    },
    {
      title: '属性',
      dataIndex: 'attribute',
    },
    {
      title: '等级',
      dataIndex: 'grade',
    },
    {
      title: '规格',
      dataIndex: 'spec',
    },
    {
      title: '数量',
      dataIndex: 'amount',
    },
    {
      title: '价格类型',
      dataIndex: 'priceType',
    },
    {
      title: '价格',
      dataIndex: 'price',
    },
    {
      title: '已排产',
      dataIndex: 'scheduledAmount',
    },
    // {
    //   title: '订单状态',
    //   dataIndex: 'status',
    //   render: (text: any) => orderStateEnum[text],
    // },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      render: (text: any) => (
        <span>{formatDate(text, 'YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 200,
      ellipsis: true,
    },
  ];
  if (
    btnPermission(history.location.pathname, [
      'btn_order_stock_edit',
      'btn_order_stock_del',
    ])
  ) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      render: (_: any, record: any) => (
        <>
          {btnPermission(history.location.pathname, 'btn_order_stock_edit') && (
            <span>
              <a
                onClick={() => {
                  if (record.orderTime) {
                    record.orderTime = moment(record.orderTime);
                  }
                  if (record.deliveryDate) {
                    record.deliveryDate = moment(record.deliveryDate);
                  }
                  detailForm.setFieldsValue({
                    ...record,
                  });
                  setVisible(true);
                  setEditId(record.id);
                  setEditItem(record);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="编辑">
                  <FormOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_order_stock_del') && (
            <span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除？"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(record.id);
                }}
              >
                <a>
                  <Tooltip mouseEnterDelay={0.5} title="删除">
                    <DeleteOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            </span>
          )}
        </>
      ),
    });
  }

  return (
    <div id={'calculate-body'} className={'spin-bg-white'}>
      <Spin tip={'权限获取中,请稍等...'} spinning={btnPermissionLoading}>
        <HehDescribe
          data={decInfo}
          columns={columns}
          visible={decVisible}
          onCancel={() => setDecVisible(false)}
        />
        <Detail
          afterClose={() => {
            setEditId(undefined);
            setEditItem(undefined);
            detailForm.resetFields();
          }}
          visible={visible}
          editId={editId}
          getForm={(from: any) => (detailForm = from)}
          loading={mergeLoading(addLoading, updateLoading)}
          onCancel={() => setVisible(false)}
          onOk={async () => {
            await detailForm.validateFields();
            const value = detailForm.getFieldsValue();
            if (value.orderTime) {
              value.orderTime = formatDateTimeStamp(value.orderTime);
            }
            if (value.deliveryDate) {
              value.deliveryDate = formatDateTimeStamp(value.deliveryDate);
            }
            if (value.orderNo) {
              delete value.orderNo;
            }
            if (value.orderType) {
              delete value.orderType;
            }
            if (editId) {
              const data = diffSubmitData(editItem, value);
              update({
                id: editId,
                ...data,
              });
            } else {
              add({
                ...value,
              });
            }
          }}
        />
        <ProTable<any>
          id={'heh-table'}
          loading={pageLoading}
          dataSource={dataSource}
          columns={columns}
          actionRef={actionRef}
          tableAlertRender={false}
          search={false}
          // scroll={x.x === '100%' ? {} : x}
          scroll={{ x: 'max-content' }}
          onColumnsStateChange={data => {
            const arr = [];
            for (let i in data) {
              if (data[i].show !== undefined) {
                arr.push(i);
              }
            }
            if (arr.length > 3) {
              setX({ x: '100%' });
            } else {
              setWidth();
            }
          }}
          options={{
            fullScreen: false,
            density: true,
            reload: false,
            setting: true,
          }}
          rowKey="id"
          size={size}
          onSizeChange={(s: any) => {
            setSize(s);
          }}
          onRow={record => {
            return {
              onDoubleClick: event => {
                setDecVisible(true);
                setDecInfo(record);
              },
            };
          }}
          headerTitle={
            btnPermission(
              history.location.pathname,
              'btn_order_stock_search',
            ) && (
              <Search
                loading={pageLoading}
                callbackValue={(value: any) => {
                  setCurrent(1);
                  setSearchValue(value);
                }}
              />
            )
          }
          toolBarRender={(action, { selectedRows }) => [
            btnPermission(history.location.pathname, 'btn_order_stock_add') && (
              <Button
                onClick={() => setVisible(true)}
                icon={<PlusOutlined />}
                type="primary"
              >
                新建
              </Button>
            ),
          ]}
          pagination={{
            pageSize: pageSize,
            total: total,
            current: current,
            onChange: (page, pageSize) => {
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {
              setCurrent(current);
              setPageSize(size);
            },
          }}
          // expandable={{
          //   expandedRowRender,
          //   onExpand: (expanded, record) => {
          //     setChildPageData({
          //       ...childPageData,
          //       [record.id]: {
          //         loading: true,
          //       },
          //     });
          //     getChildPage({
          //       pageNo: 1,
          //       pageSize: 10,
          //       parentId: record.id,
          //     });
          //   },
          //   rowExpandable: record => {
          //     return true;
          //   },
          // }}
        />
      </Spin>
    </div>
  );
};
export default connect(({ globalModel, MainLayoutModel }: any) => ({
  btnPermissionLoading: globalModel.btnPermissionLoading,
  childrenCollapsed: MainLayoutModel.childrenCollapsed,
}))(List);
